package com.leo.nio.filechannel;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author du
 */
public class MappedByteBufferTest {
    public static void main(String[] args) throws IOException {

        RandomAccessFile randomAccessFile = new RandomAccessFile("d:\\1.txt", "rw");
        FileChannel channel = randomAccessFile.getChannel();

        /**
         * 内存映射, 使用直接内存(堆外内存)
         * 参数1: 读写模式
         * 参数2: 映射的起始位置
         * 参数3: 映射的内存大小 (不是索引位置), 即可修改的范围是1-5, 对应索引是0-4
         * 实际类型: DirectByteBuffer
         */
        MappedByteBuffer mappedByteBuffer = channel.map(
                FileChannel.MapMode.READ_WRITE, 0, 5);
        mappedByteBuffer.put(0, (byte)'1');
        mappedByteBuffer.put(3, (byte)'3');
        mappedByteBuffer.put(5, (byte)'5'); //IndexOutOfBoundsException

        randomAccessFile.close();
    }
}
